import 'package:app/api/material-pick/material.dart';
import 'package:app/components/index.dart';
import 'package:flutter/material.dart';

import '../../api/heat-treatment/index.dart';
import 'package:qrscan/qrscan.dart' as scanner;

import '../../util/StringUtils.dart';

///热处理配送
class HeatTreatment extends StatefulWidget {
  const HeatTreatment({super.key});
  @override
  State<HeatTreatment> createState() => HeatTreatmentState();
}

class HeatTreatmentState extends State<HeatTreatment> {
  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();
  final FocusNode _firstFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });
  }

  //站点码
  String _code = "";
  //设置开始配送按钮是否可用
  bool isButtonEnabled = false;
  ///设置表单值
  List<dynamic> _data = [];

  @override
  void dispose() {
    super.dispose();
    _firstFocusNode.dispose();
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void scan() async{
    String? qrCode = await scanner.scan();
    setState(() => _code = qrCode.toString());
  }

  void setValue(String key, String value, bool bool) {
    switch (key) {
      case '_code':
        _code = value;
      case 'isButtonEnabled':
        isButtonEnabled = bool;
        break;
      default:
        throw Exception("key error");
    }
  }

  /// 开始配送
  void submit() {
    Forms.validate(_formKey!).then((valid){
      if(valid){
        HeatTreatmentApi.of(context).createDelivery({
          'code': _code,
          'pick': _data[0]['pickId'],
          'container': _data[0]['container']
        }).then((res){
          if (StringUtils.isNotNull(res.data) && StringUtils.isNotNull(res)) {
            Success.of(context).show('配送成功!');
          }
        });
      }
    });
  }

  /// 确认
  void confirm(){
    MaterialApi.of(context).list(_code).then((res){
      _data = res.data['data'];
    });
  }

  void go(String path){
    Navigator.pushNamed(context, path);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '热处理配送'),
      body: GestureDetector(
        onTap: hideKeyBorder,
        child: Column(
          children: [
            Group(
              title: '操作',
              height: 120,
              context: context,
              child: Menu(context: context, items: [
                MenuItem(
                  icon: const Icon(Icons.add, color: Colors.white, size: 40),
                  text: "物料拣配",
                  color: const Color.fromARGB(255, 154, 204, 109),
                  onTap: () => go('/material-pick'),
                ),
                MenuItem(
                  icon: const Icon(Icons.call, color: Colors.white, size: 40),
                  text: "空托呼叫",
                  color: const Color.fromARGB(255, 109, 183, 234),
                  onTap: () => go('/empty-pallet-call'),
                ),
              ]),
            ),
            Group(
              context: context,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Forms(
                    formKey: _formKey,
                    formItem: [
                      FormItem(
                        type: 'input',
                        labelWidth: 90,
                        focusNode: _firstFocusNode,
                        labelText: '站 点 码:',
                        placeholder: '请扫描站点码',
                        filedName: 'code',
                        icon: const Icon(Icons.qr_code_scanner_rounded),
                        value: _code,
                        iconOnTap: scan,
                        onEntry: (value)=>{confirm()},
                        onChange: (value) =>
                            setValue('_code', value, isButtonEnabled = true),
                        rules: const {
                          'code': [
                            {'required': true, 'message': '站点码不能为空'}
                          ]
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Expanded(
              child: ListContainer(
                title: '物料清单',
                length: _data.length,
                children: (index) {
                  return [
                    ListTitle(
                      context: context,
                      label: _data[index]['itemName'],
                    ),
                    Horizontal(
                      items: [
                        HorizontalItem(
                          label: "托盘号：",
                          fontColor: Colors.white,
                          value: _data[index]['container'],
                          valueBackground: Colors.green,
                        )
                      ],
                    ),
                    Horizontal(
                      items: [
                        HorizontalItem(
                          label: "物料编码：",
                          value: _data[index]['itemCode'],
                        ),
                      ],
                    ),
                    Horizontal(
                      items: [
                        HorizontalItem(
                          label: "任  务  号：",
                          value: _data[index]['itemWorkCode'],
                        ),
                        HorizontalItem(
                          label: "数量：",
                          fontColor: const Color.fromARGB(255, 255, 255, 255),
                          value: _data[index]['itemQty'].toString() + " " + _data[index]['itemUnit'],
                          valueBackground: const Color.fromARGB(255, 110, 182, 239),
                        )
                      ],
                    ),
                  ];
                },
              ),
            ),
            SizedBox(
              width: MediaQuery.of(context).size.width,
              child: Padding(
                padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
                child: Button(
                  onPressed: isButtonEnabled && _data.isNotEmpty ? submit : null,
                  backgroundColor: isButtonEnabled
                      ? const Color.fromARGB(255, 60, 98, 60)
                      : Colors.grey,
                  label: '开始配送',
                  height: 60,
                  fontSize: 18,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}